<template>
	<el-dialog v-model="dialog" title="分配菜单" width="50%" destroy-on-close v-loading="loading">
		<el-tree ref="menuRef" :data="state.menuList" :props="defaultProps" node-key="id" show-checkbox @check="handleChange">
			<template #default="{ node, data }">
				<span class="custom-tree-node">
					<span>{{ $t(node.label) }}</span>
				</span>
			</template></el-tree
		>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialog = false">取 消</el-button>
				<el-button type="primary" @click="onsubmit" :loading="loading">确 认</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick } from 'vue';
import { getList, getMenusByRole } from '/@/api/upms/menu';
import { saveRoleMenu, getByTenantId } from '/@/api/upms/sysrole';
import { ElMessage } from 'element-plus';
interface State {
	menuList: Array<any>;
	menuIds: Array<string>;
	sysRole: any;
}
const emit = defineEmits(['initPage']);
const menuRef = ref();
const dialog = ref(false);
const state = reactive<State>({ menuList: [], menuIds: [], sysRole: {} });
const loading = ref(false);
const defaultProps = ref({
	children: 'children',
	label: 'name',
	disabled: 'disabled',
});
/**
 * 选择菜单权限事件
 */
const handleChange = () => {
	let checkedKeys = menuRef.value.getCheckedKeys(false);
	let halfCheckedKeys = menuRef.value.getHalfCheckedKeys(false);
	state.menuIds = [...checkedKeys, ...halfCheckedKeys];
};

/**
 * 获取指定角色的菜单
 */
const getTenantMenus = async (id: string) => {
	/**
	 * 查询菜单树数据
	 */
	await getList().then((response) => {
		state.menuList = response.data.data;
	});
	await getByTenantId(id).then((response) => {
		state.sysRole = response.data.data;
	});
	await getMenusByRole({ roleId: state.sysRole.id, tenantId: id }).then((response) => {
		state.menuIds = response.data.data;
		if (state.menuIds) {
			state.menuIds.forEach((id: string) => {
				nextTick(() => {
					menuRef.value.setChecked(id, true, false);
				});
			});
		}
	});
};
const onsubmit = () => {
	loading.value = true;
	saveRoleMenu({ roleId: state.sysRole.id, menuIds: state.menuIds }).then(() => {
		loading.value = false;
		ElMessage.success('更新成功');
		dialog.value = false;
		emit('initPage');
	});
};
const initMenu = (id: string) => {
	dialog.value = true;
	getTenantMenus(id);
};
defineExpose({
	initMenu,
});
</script>
<style>
.hx-menus {
	height: 500px;
	overflow-y: auto;
	width: 100%;
	border: 1px solid #dcdee0;
	padding: 4px;
	border-radius: 4px;
}
</style>
